package com.axing.springbootinit.service.impl;

import com.axing.springbootinit.common.ErrorCode;
import com.axing.springbootinit.exception.BusinessException;
import com.axing.springbootinit.mapper.UserInterfaceInfoMapper;
import com.axing.model.entity.UserInterfaceInfo;
import com.axing.springbootinit.service.UserInterfaceInfoService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
* @author 13921
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2025-03-31 16:59:23
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public void validUserInterfaceInfo(com.axing.model.entity.UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Integer totalNum = userInterfaceInfo.getTotalNum();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        // 创建时，参数不能为空
        if (!add) {
            if (userId <= 0 || interfaceInfoId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
            }

            if (leftNum <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于0");
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean invokeCount(Long interfaceId, Long userId) {
        boolean update = false;
        RLock lock = redissonClient.getLock("axing:precachejob:docache:lock");
        try {
            // 只有一个线程能获取到锁
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                // todo 实际要执行的方法
                //判断
                if (interfaceId <= 0 || userId <= 0) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                UpdateWrapper<UserInterfaceInfo> userInterfaceInfoUpdateWrapper = new UpdateWrapper<>();
                userInterfaceInfoUpdateWrapper.eq("userId", userId);
                userInterfaceInfoUpdateWrapper.eq("interfaceInfoId", interfaceId);
                userInterfaceInfoUpdateWrapper.gt("leftNum", 0);
                // 事务管理  || 加锁 高并发
                userInterfaceInfoUpdateWrapper.setSql("leftNum =leftNum - 1 , totalNum =totalNum + 1 ");
                update = this.update(userInterfaceInfoUpdateWrapper);
            }
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        } finally {
            // 只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
        return update;
    }





}



